package com.itheima.comfyui.core.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.itheima.comfyui.core.dto.common.Result;
import com.itheima.comfyui.core.dto.common.ResultCode;
import com.itheima.comfyui.core.pojo.User;
import com.itheima.comfyui.core.util.JWTUtils;
import com.itheima.comfyui.core.util.UserUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

public class UserInterceptor implements HandlerInterceptor {


    /**
     * 拦截前逻辑
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从resquest中取token
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        //判断是否取到token
        if(StrUtil.isEmpty( header)){
            writeErrMsg(response);
            return false;
        }
        //验证token
        if(!JWTUtils.verify(header)){
            writeErrMsg(response);
            return false;
        }
        User user = JWTUtils.getUser(header);
        UserUtils.setUser(user);
        return true;
    }


    private void writeErrMsg(HttpServletResponse response) {
        //设置状态码及响应头
        //状态
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        //字符类型
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //编码格式
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        //设置响应体内容
        try (PrintWriter writer = response.getWriter()) {
            Result<Object> result = Result.failed(ResultCode.ACCESS_UNAUTHORIZED);
            writer.print(JSONUtil.toJsonStr(result));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 拦截后逻辑
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       //移除 用户
        UserUtils.clearUser();
    }
}
